package com.kzj.laimeimei.activity;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;


import com.kzj.laimeimei.R;
import com.kzj.laimeimei.global.App;
import com.kzj.laimeimei.global.Constant;
import com.kzj.laimeimei.global.CrashHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 查看服务器请求/响应日志
 *
 */
public class ServerLogActivity extends GBaseActivity  {

	private static String TAG = "ServerLog";
	String curFileName = null;
	TextView tv_show = null;
	ScrollView scrol = null;
	private static String dirPath = "GMALL_log_data";

	public static SimpleDateFormat DB_DATE_FORMAT_NORMAL = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	final String path_server = Environment.getExternalStorageDirectory()
			.getPath() + "/" + dirPath + "/server";
	final String path_crash = Environment.getExternalStorageDirectory()
			.getPath() + "/" + dirPath + "/crash";
	public static Boolean isCrash = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		scrol = new ScrollView(this);
		LinearLayout layout = new LinearLayout(this);
		scrol.setBackgroundColor(Color.WHITE);
		tv_show = new TextView(this);
		tv_show.setTextColor(Color.BLACK);
		tv_show.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
		tv_show.setGravity(Gravity.CENTER);
		layout.addView(tv_show, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		scrol.addView(layout, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		setContentView(scrol);

		// setContentView(R.layout.req_and_res_log);
		// tv_show=(TextView) findViewById(R.id.tv_show);
		if (!TextUtils.isEmpty(getIntent().getStringExtra("crash"))) {
			isCrash = true;
			setTopTitle("crash日志");
		} else {
			isCrash = false;
			setTopTitle("response日志");
		}
		setLeftImg(View.VISIBLE, R.drawable.selector_back);
		setRightText(View.VISIBLE, "清空");
		new LoadTask().execute();
	}

	@Override
	protected void findViewByIds() {

	}
	@Override
	protected void initDatas() {

	}

	@Override
	protected void fillArrayInListView() {

	}


	@Override
	public void doClickRightText() {
		super.doClickRightText();
		clearLog();
		tv_show.setText("没有日志记录");
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	class LoadTask extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			String tmp = "";
			if (isCrash) {
				tmp = getLogString(path_crash);
			} else {
				tmp = getLogString();
			}
			return tmp;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result != null) {
				tv_show.setText(result);
				scroll2Bottom(scrol, tv_show);
			} else {
				tv_show.setText("没有日志记录");
			}
		}
	}

	public static void scroll2Bottom(final ScrollView scroll, final View inner) {
		Handler handler = new Handler();
		handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (scroll == null || inner == null) {
					return;
				}
				// 内层高度超过外层
				int offset = inner.getMeasuredHeight()
						- scroll.getMeasuredHeight();
				if (offset < 0) {
					Log.v("scroll2Bottom", "定位...");
					offset = 0;
				}
				scroll.scrollTo(0, offset);
			}
		});
	}

	public static boolean isSDCardExist() {
		String status = Environment.getExternalStorageState();
		boolean flag = status.equals(android.os.Environment.MEDIA_MOUNTED);
		// LogUtils.logd("SDCardUtil", "检查SD卡结果： "+
		// ""+((flag)?"可读  ":"不可读  ")+"\n"+"SDCard Status - " + status+" "+"\n"
		// + ".....................! \n"+ " current time is: "
		// + new Timestamp(System.currentTimeMillis()).toString());
		return flag;

	}

	private String getLogString() {
		// int onceSize=1024*1024;
		// int allSize=0;

		try {
			curFileName = getTodayLogFullName(path_server + "/");
			FileInputStream stream = null;
			File file = new File(curFileName);
			if (!isSDCardExist()) {
				return null;
			}
			if (!file.exists()) {
				return null;
			}
			stream = new FileInputStream(file);
			// allSize=stream.available();
			byte[] bytes = new byte[stream.available()];
			stream.read(bytes);
			String content = new String(bytes);
			stream.close();
			return content;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	private String getLogString(String path) {
		// int onceSize=1024*1024;
		// int allSize=0;

		try {
			curFileName = getTodayLogFullName(path + "/");
			FileInputStream stream = null;
			File file = new File(curFileName);
			if (!isSDCardExist()) {
				return null;
			}
			if (!file.exists()) {
				return null;
			}
			stream = new FileInputStream(file);
			// allSize=stream.available();
			byte[] bytes = new byte[stream.available()];
			stream.read(bytes);
			String content = new String(bytes);
			stream.close();
			return content;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
	public static void saveRequest2File(String s, String reqAddr) {
		if (Constant.SystemContext.isDebugLog) {
			isCrash = false;
			StringBuffer strb = new StringBuffer(
					"=================Request=================\n");
			strb.append("URL:"+s);
			strb.append(reqAddr + "\n \n");

			strb.append("=================End=================\n");

			Log.d(TAG, strb.toString());
			saveInfo2File(strb.toString());
			if (Constant.SystemContext.isDebugShowToast) {
				App.showToast(strb.toString());
			}
			//GBaseToastUtil.showToast(AppConfig.getInstance(), strb.toString());
		}

	}
	public static void saveRequest2File(RequestParams params, String reqAddr) {
		if (Constant.SystemContext.isDebugLog) {
			isCrash = false;
			StringBuffer strb = new StringBuffer(
					"=================Request=================\n");
			strb.append("URL:");
			strb.append(reqAddr + "\n \n");
			String[] sArray = params.toString().split("&");
			for (String s1 : sArray) {
				strb.append(s1);
				strb.append(";\n");
			}
			strb.append("=================End=================\n");
			Log.i(TAG, reqAddr + "?" + params.toString());
			Log.d(TAG, strb.toString());
			saveInfo2File(strb.toString());
			if (Constant.SystemContext.isDebugShowToast) {
				App.showToast(strb.toString());
			}
			//GBaseToastUtil.showToast(AppConfig.getInstance(), strb.toString());
		}

	}

	public static void saveResponse2File(RequestParams params, String jsonStr,
										 String time) {
		if (Constant.SystemContext.isDebugLog) {
			if (!TextUtils.isEmpty(jsonStr)) {

				isCrash = false;

				StringBuffer strb = new StringBuffer(
						"---------------------Response--------------------- \n");
				// strb.append(clz.getSimpleName()+":\n \n ");

				strb.append("服务器返回的时间差：" + time);
				strb.append(";\n");
				String[] sArray = params.toString().split("&");
				for (String s1 : sArray) {
					strb.append(s1);
					strb.append(";\n");
				}
				String[] jsonItems = jsonStr.split(",");
				for (String string : jsonItems) {
					strb.append("  " + string + "\n");
				}
				strb.append("-----------------------End----------------------- \n");

				Log.d(TAG, strb.toString());

				saveInfo2File(strb.toString());
			}
		}
	}

	public static void saveResponse2File(String jsonStr) {
		if (Constant.SystemContext.isDebugLog) {
			if (!TextUtils.isEmpty(jsonStr)) {

				isCrash = false;
				StringBuffer strb = new StringBuffer(
						"---------------------Response--------------------- \n");
				// strb.append(clz.getSimpleName()+":\n \n ");
				String[] jsonItems = jsonStr.split(",");
				for (String string : jsonItems) {
					strb.append("  " + string + "\n");
				}
				strb.append("-----------------------End----------------------- \n");

				Log.d(TAG, strb.toString());

				saveInfo2File(strb.toString());
			}}
	}

	public static void saveBroadcast2File(String jsonStr) {
		if (Constant.SystemContext.isDebugLog) {
			if (!TextUtils.isEmpty(jsonStr)) {

				isCrash = false;
				StringBuffer strb = new StringBuffer(
						"---------------------Broadcast广播--------------------- \n");
				// strb.append(clz.getSimpleName()+":\n \n ");
				String[] jsonItems = jsonStr.split(",");
				for (String string : jsonItems) {
					strb.append("  " + string + "\n");
				}
				strb.append("-----------------------End----------------------- \n");

				Log.d(TAG, strb.toString());

				saveInfo2File(strb.toString());
			}}
	}

	public static String saveCatch2File(Exception ex) {

		StringBuffer sb = new StringBuffer();
		sb.append("====================这里开始========================\n");

		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		System.currentTimeMillis();
		String time = DB_DATE_FORMAT_NORMAL.format(new Date());

		sb.append(result);
		sb.append("============================================\n"
				+ android.os.Build.MODEL);
		sb.append("\n");
		sb.append(time);
		sb.append("\n============================================\n");
		try {

			String fileName = "crash_log_"
					+ (Calendar.getInstance().get(Calendar.MONTH) + 1) + "_"
					+ Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
					+ ".txt";
			// String fileName = "crash-" + time + "-" + timestamp + ".txt";
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// String path = "/sdcard/crash/";
				String path = CrashHandler.CRASH_PATH;
				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(path + fileName,
						true);
				fos.write(sb.toString().getBytes());
				fos.close();
			}
			return fileName;
		} catch (Exception e) {
			Log.e(TAG, "an error occured while writing file...", e);
		}
		return null;
	}

	public static String saveSpecialString2File(String info, String desc) {
		if (Constant.SystemContext.isDebugLog) {

			StringBuffer sb = new StringBuffer();
			sb.append("====================这里开始========================\n");
			sb.append(desc + "\n");

			System.currentTimeMillis();
			String time = DB_DATE_FORMAT_NORMAL.format(new Date());

			sb.append(info);
			sb.append("============================================\n"
					+ android.os.Build.MODEL);
			sb.append("\n");
			sb.append(time);
			sb.append("\n============================================\n");
			try {

				String fileName = "crash_log_"
						+ (Calendar.getInstance().get(Calendar.MONTH) + 1)
						+ "_"
						+ Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
						+ ".txt";
				// String fileName = "crash-" + time + "-" + timestamp + ".txt";
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// String path = "/sdcard/crash/";
					String path = CrashHandler.CRASH_PATH;
					File dir = new File(path);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					FileOutputStream fos = new FileOutputStream(
							path + fileName, true);
					fos.write(sb.toString().getBytes());
					fos.close();
				}
				return fileName;
			} catch (Exception e) {
				Log.e(TAG, "an error occured while writing file...", e);
			}
		}
		return null;
	}

	public static void saveHuXin(String jsonStr, boolean result, String reason) {
		if (Constant.SystemContext.isDebugLog) {
			if (!TextUtils.isEmpty(jsonStr)) {

				isCrash = false;
				StringBuffer strb = new StringBuffer(
						"---------------------HuanXin--------------------- \n");

				strb.append(jsonStr + "\n");
				if (result) {
					strb.append("环信登录成功" + "\n");
				} else {
					strb.append("环信登录失败" + "\n");
				}
				strb.append("原因是--" + reason + " \n");
				strb.append("-----------------------End----------------------- \n");

				Log.d(TAG, strb.toString());

				saveInfo2File(strb.toString());
			}}
	}

	private static String getTodayLogFullName(String path) {
		String fileName = "";
		if (isCrash) {
			fileName = "crash_log_"
					+ (Calendar.getInstance().get(Calendar.MONTH) + 1) + "_"
					+ Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
					+ ".txt";
		} else {
			fileName = "sever_log_"
					+ (Calendar.getInstance().get(Calendar.MONTH) + 1) + "_"
					+ Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
					+ ".txt";
		}
		return path + fileName;
	}

	/*
	 * private static String getTodayLogFullName(){ String path =
	 * Environment.getExternalStorageDirectory
	 * ().getPath()+"/"+dirPath+"/server/"; String fileName =
	 * "sever_log_"+(Calendar
	 * .getInstance().get(Calendar.MONTH)+1)+"_"+Calendar.getInstance
	 * ().get(Calendar.DAY_OF_MONTH)+".txt"; return path + fileName; }
	 */

	/**
	 * 保存信息到文件中
	 */
	public static Void saveInfo2File(String info) {

		StringBuffer sb = new StringBuffer();
		Date date = new Date(System.currentTimeMillis());
		String time = DB_DATE_FORMAT_NORMAL.format(date);
		sb.append("\n");
		sb.append("Log time - " + time + "##  currentTimeMillis - "
				+ System.currentTimeMillis());
		sb.append("\n");
		sb.append(info);
		try {
			final String path = Environment.getExternalStorageDirectory()
					.getPath() + "/" + dirPath;
			String path2 = "";
			if (isCrash) {
				path2 = path + "/crash/";
			} else {
				path2 = path + "/server/";
			}

			final String filePath = getTodayLogFullName(path2);
			if (isSDCardExist()) {
				final File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdir();
				}
				final File dir2 = new File(path2);
				if (!dir2.exists()) {
					dir2.mkdir();
				}
				File file = new File(filePath);
				if (!file.exists()) {
					file.createNewFile();
				}

				FileOutputStream fos = new FileOutputStream(filePath, true);
				fos.write(sb.toString().getBytes());
				fos.close();
			}
		} catch (Exception e) {
			Log.e("ReqAndResLogActivity",
					"an error occured while writing file...", e);
			if (e != null)
				e.printStackTrace();
		}
		return null;
	}

	// 删除文件
	public void delFile(File file) {
		try {
			file.delete();
		} catch (Exception e) {
			System.out.println("删除文件操作出错");
			Log.e("FileUtil", "删除文件操作出错");
			e.printStackTrace();
			Log.e("FileUtil", e.toString());
		}
	}

	/**
	 * 清除所有日志
	 */
	public void clearLog() {
		String path = "";
		if (isCrash) {
			path = path_crash + "/";
		} else {
			path = path_server + "/";
		}
		File dir = new File(path);
		if (dir != null&& dir.exists()) {
			for (File afile : dir.listFiles()) {
				if (afile != null) {
					delFile(afile);
				}
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "清除所有日志");
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case 0:
				clearLog();
				tv_show.setText("没有日志记录");
				finish();
				break;
		}
		return true;

	}

}
